<template>
    <div>
        <div style="margin: 20px 20px;" class="btn_box">
            <el-button type="primary" @click="handlerAdd">新增学校</el-button>
        </div>
        <el-table :data="schools" style="width: 100%;height: 380px;" border>
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column type="schoolname" label="学校名称" prop="schoolname"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row._id)">
                        编辑
                    </el-button>
                    <el-button type="danger" @click="handleDelete(scope.row._id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

        <!-- 新增学校 -->
        <el-dialog v-model="schoolFromVisible" :title="title" width="500">
            <el-form :model="schoolFrom" ref="schoolFormRef" :rules="rules">
                <el-form-item label="学校名称" prop="schoolname">
                    <el-input v-model="schoolFrom.schoolname" @keydown.enter = "submitForm(schoolFormRef)"/>
                </el-form-item>
                
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(schoolFormRef)">
                        确定
                    </el-button>
                    <el-button @click="schoolFromVisible = false">取消</el-button>
                    
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<script setup lang="ts">
import type { schoolInfoData, schoolPageData, schoolTotalData } from '@/api/school/type';
import useSchoolStore from '@/store/modules/school';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue';
const schoolStore = useSchoolStore()
const schools = ref<schoolInfoData[]>()

/* 获取学校的分页查询 */
//当前页码:
const currentPage = ref(1);
//每页展示多少
const pageSize = ref(5);
//分页返回的总条数
const total = ref(0)

//分页查询方法
const PageQuery = () =>{
    schoolStore.pageSchool({page:currentPage.value,size:pageSize.value}).then((res) => {
        schools.value = res.data as schoolInfoData[];
        total.value = res.total;
    })
}
//显示条数大小改变的时候触发的方法
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    PageQuery()
    console.log(`当前一页总条数:${val}`);
}
//改变当前页面
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    PageQuery()
    console.log(`当前页码:${val}`);
}

/* 新增学校 */
//控制新增或更新学校对话框显隐
const schoolFromVisible = ref(false);
//
const title = ref<string>()
//学校对象,用来做数据保存
const schoolFrom = ref<schoolInfoData>({
    _id:undefined,
    schoolname:"",
  
    
})
const schoolFormRef = ref<FormInstance>()
//点击新增学校按钮触发的方法
const handlerAdd = () => {
    schoolFromVisible.value = true;
    title.value = "新增学校";
    nextTick(()=>{
        schoolFormRef.value?.resetFields();
    })
}





/* 编辑学校信息 */
const handleEdit = (_id:string)=>{
    console.log("_id:",_id);
    
    schoolFromVisible.value = true;
    title.value = "编辑学校";
    schoolStore.findById(_id).then((res)=>{
        schoolFrom.value = {...res};
        console.log(schoolFrom.value);
        
    })
}
const checkSchoolName = (rule: any, value: any, callback: any) => {
    value = value.trim();
    const schoolNameReg = /.*(学院|大学)$/;
  if (value == "") {
    return callback(new Error('请输入学校名称'))
  }else if(!schoolNameReg.test(value)){
    return callback(new Error('请输入正确的学校名称'))
  }else{
    return callback();
  }
}

const rules = reactive<FormRules>({
  schoolname: [{ required:true,validator: checkSchoolName, trigger: 'blur' }],

})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
        if(title.value == "新增学校"){
            //验证都成功后,发送添加请求
        schoolStore.addSchool(schoolFrom.value).then(()=>{
            //刷新页面
            PageQuery();
            //关掉对话框
            schoolFromVisible.value = false
            ElMessage({
                type:'success',
                message:"添加成功"
            })
        }).catch((err)=>{
            schoolFromVisible.value = false
            ElMessage({
                type:"error",
                message:err.msg
            })
        })
        }else if(title.value == "编辑学校"){
            //编辑学校的校验
            
            
            schoolStore.updateSchool(schoolFrom.value).then(()=>{
                //刷新页面
                PageQuery();
                //关掉对话框
                schoolFromVisible.value = false
                ElMessage({
                type:'success',
                message:"修改成功"
                })
            }).catch((err)=>{
                schoolFromVisible.value = false
                ElMessage({
                    type:"error",
                    message:err.msg
                })
            })
            
        }
    } else {
      console.log('error submit!')
    }
  })
}

/* 删除学校 */
const handleDelete = (_id: string) => {
    schoolStore.removeSchool(_id).then(() => {
        //删除成功
       PageQuery()
        ElMessage({
            type: "success",
            message: "删除成功"
        })
    }).catch((err)=>{
        ElMessage({
            type: "error",
            message: err.msg
        })
    })

}
onMounted(() => {
    PageQuery()
})
</script>

<style scoped>
.el-pagination {
    display: flex;
    justify-content: center;
}
</style>